import { _decorator, Component, director, Node, Sprite, Animation, SpriteFrame, UITransform, Prefab, instantiate } from 'cc';
import { aa } from '../frame/FrameCore';
import Net from '../frame/managers/NetMgr';
import builder from '../deco/RoomBuilder';
import DecoUtil from '../deco/DecoUtils';
import configs from '../Configs';
const { ccclass, property } = _decorator;

@ccclass('RectCtrl')
export class RectCtrl extends Component {

    @property(Sprite)
    sp: Sprite = null;
    @property
    isSmall = true;
    @property(Animation)
    loadAnm: Animation = null;

    public callback: Function = null;
    private _uuid = null;
    private _roomData = null;
    public glb: string = null;
    private type = null;
    public scale = 0.35;
    public prefab: Prefab = null;

    init(cb?: Function, base64?: string) {
        cb && (this.callback = cb);
    }
    start() {
        this.node.on(Node.EventType.TOUCH_END, () => {
            this.callback && this.callback();
        }, this);
    }
    setObj(obj: any) {
        this.scale = obj.scale;
        this.prefab = obj.model;
        this.setSP(obj.sp);
        this.callback = () => {
            const model = instantiate(this.prefab);
            DecoUtil.addModelToScene(model, this.scale)
        }

    }


    async setSpFromPrompt(prompt: string, type?: number) {
        this.loadAnm.node.active = true;
        this.loadAnm.play();
        const res = await Net.fetchGet(configs.serverUrl, { prompt: prompt })
        this.type = type;
        if (res.uuid) {
            this._uuid = res.uuid;
            this.callback = () => {
                this.createModel();
            }
        }
        if (res.base64) {
            const base64 = res.base64;
            const tex = await aa.utils.createTexWithBase64("test", base64);
            const sp = new SpriteFrame();
            sp.texture = tex;
            this.setSP(sp);
            this.loadAnm.node.active = false;
            this.loadAnm.stop();
        }

    }


    async setSpFromBase64(base64: string, task?: string) {
        if (base64 !== null && base64.length > 0) {
            const tex = await aa.utils.createTexWithBase64("test", base64);
            const sp = new SpriteFrame();
            sp.texture = tex;
            this.setSP(sp);
        }

        if (this.isSmall) {
            this.callback = () => {
                this.createModel();
            }
            if (task) {
                this._uuid = task;
            } else {
                if (base64) {
                    const res = await DecoUtil.createModel(base64);
                    this._uuid = res.uuid;
                }
            }
        } else {
            if (base64) {
                aa.ui.isLoading();

                this._roomData = await Net.recognizeDrawing(base64);
                if (this._roomData) {
                    this._roomData.wallpoints.forEach((w) => {
                        w.x = -w.x * builder.scale;
                        w.y = w.y * builder.scale;
                    });
                    this._roomData.doors.forEach((door) => {
                        door.pos.x *= -builder.scale;
                        door.pos.y *= builder.scale;

                    });

                    this._roomData.rooms.forEach((room) => {
                        room.pos.x *= -builder.scale;
                        room.pos.y *= builder.scale;
                    });

                    this.callback = () => {
                        builder.createRoom(this._roomData);
                    }
                    builder.createRoom(this._roomData);
                }
                aa.ui.putLoading();

            }

        }
    }
    async createModel() {
        console.log("createdModel", this._uuid)
        if (this._uuid) {
            let info = null;
            const type = builder.type[this.type];
            if (type) {
                const best = builder.bestPos[type];
                if (best) {
                    info = best;
                }
            }
            const scale = builder.scales[this.type] || this.scale;
            const rotate = builder.rotate[this.type] || 0;

            if (this.glb) {
                await DecoUtil.loadRemoteModel(this.glb, scale, info, rotate)

            } else {
                const res = await DecoUtil.checkModel(this._uuid);
                if (!res.glb) {
                    console.log("GLB file not ready yet");
                    aa.ui.toast("GLB file not ready yet")
                } else {
                    console.log("glb=="+res.glb)
                    this.glb = res.glb
                }
                await DecoUtil.loadRemoteModel(this.glb, scale, info, rotate)

            }

        }
    }

    setSP(sp: SpriteFrame) {
        const maxSize = this.isSmall ? 134 : 142;

        let width, height
        if (sp.width && sp.height) {

            width = sp.width;
            height = sp.height;

            // 计算缩放比例，保持宽高比
            const scaleX = maxSize / width;
            const scaleY = maxSize / height;
            const scale = Math.min(scaleX, scaleY); // 取最小的缩放比例，确保不超过任何一个维度的限制
            // 计算最终尺寸
            width *= scale;
            height *= scale;
        } else {
            width = height = maxSize
        }

        this.sp.spriteFrame = sp;
        // 设置节点的contentSize
        this.sp.node.getComponent(UITransform).setContentSize(width, height);
    }


}

